package org.netty.handler;

import com.webside.netty.enums.MsgType;
import com.webside.netty.model.*;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.SocketChannel;
import org.netty.util.NettyChannelMap;

public class NettyServerHandler extends SimpleChannelInboundHandler<BaseMsg>{


    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, BaseMsg baseMsg) throws Exception {

        MsgType type = baseMsg.getType();

        if(MsgType.LOGIN.equals(type))
        {
            LoginMsg loginMsg = (LoginMsg)baseMsg;
            if("wjggwm".equals(loginMsg.getUserName()) && "wjggwm".equals(loginMsg.getPassword()))
            {
                //登录成功，把channel存到服务器的channel map中
                NettyChannelMap.add(loginMsg.getClientId(), (SocketChannel) channelHandlerContext.channel());
                System.out.println("client:" + loginMsg.getClientId() + " 登录成功");
            }
        }else
        {
            if(null == NettyChannelMap.get(baseMsg.getClientId()))
            {
                LoginMsg loginMsg = new LoginMsg();
                channelHandlerContext.channel().writeAndFlush(loginMsg);
            }
        }

        switch(type)
        {
            case ASK:
            {
                //收到客户端的请求
                AskMsg askMsg=(AskMsg)baseMsg;
                if("authToken".equals(askMsg.getParams().getAuth()))
                {
                    ReplyServerBody replyBody=new ReplyServerBody("server info $$$$ !!!");
                    ReplyMsg replyMsg=new ReplyMsg();
                    replyMsg.setBody(replyBody);
                    NettyChannelMap.get(askMsg.getClientId()).writeAndFlush(replyMsg);
                }
            }
            break;
            case PING:
            {
                PingMsg pingMsg = (PingMsg)baseMsg;
                PingMsg replyMsg = new PingMsg();
                NettyChannelMap.get(pingMsg.getClientId()).writeAndFlush(replyMsg);
                break;
            }
            case REPLY:
            {
                ReplyMsg replyMsg = (ReplyMsg)baseMsg;
                ReplyClientBody replyClientBody = (ReplyClientBody) replyMsg.getBody();
                System.out.println("receive client msg:" + replyClientBody.getClientInfo());
            }
                break;
            default:
                break;
        }

    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        NettyChannelMap.remove((SocketChannel) ctx.channel());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
